package com.joymart.recipient.service;

import com.joymart.recipient.model.City;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.joymart.common.utils.CollectionUtils.asList;


@Service
public class CityService {

    private List<City> cities = new ArrayList<>();

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;

    @PostConstruct
    public void init() {
      cities =  asList(jdbcAggregateTemplate.findAll(City.class));
    }

    public String parse(String district) {
       return cities.stream().filter(
           c -> district.startsWith(c.getProvince()+c.getName())
        ).findFirst().map(City::getName).orElse(district);
    }

    public String parseProvince(String district) {
        return cities.stream().filter(
                c -> district.startsWith(c.getProvince()+c.getName())
        ).findFirst().map(City::getProvince).orElse(district);
    }
}
